package me.w70.bot.methods;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.Random;

import javax.swing.KeyStroke;

public class Typer extends Helper implements KeyListener {
	private Robot robot;

	boolean dosend = true;

	TyperQueue q;

	/**
	 * Gets a char array of "oldStr"
	 * 
	 * @param oldStr
	 *            The string we're converting
	 * @return OldStr in a char array
	 */
	static char[] getCharArray(String oldStr) {
		return oldStr.toCharArray();
	}

	/**
	 * Runs the autotalker.
	 * 
	 * @param args
	 *            The arguments we're running the autotalker with, first arg is
	 *            times, second arg is message.
	 * 
	 */
	public Typer(TyperQueue q) {
		this.q = q;
		try {
			robot = new Robot();
			robot.delay(1000);
		} catch (AWTException e) {
			System.out.println(e.getCause().getMessage());
		}
		// WTF MAN WTF MAN
	}

	public void run() {
		try {
			while (true) {

				HashMap work = q.getWork();
				System.out.println(work);
				String tmessage = (String) work.get("message");
				boolean send = (Boolean) work.get("send");

				char[] messageArray = getCharArray(tmessage);
				Random gen = new Random();
				KeyStroke ks;
				int lastcode = 0;
				int average = gen.nextInt(300);

				robot.delay(200);

				for (int x = 0; x < messageArray.length; x++) {
					char l = messageArray[x];
					int mod = gen.nextInt(100);
					robot.setAutoDelay(mod + average);
					int code = 0;
					boolean shift = false;
					if (Character.toString(l).equals(
							Character.toString(l).toUpperCase())
							&& Character.isLetter(l)) {
						shift = true;

						robot.keyPress(KeyEvent.VK_SHIFT);
					}
					try {
						code = (KeyStroke.getKeyStroke("pressed "
								+ Character.toUpperCase(messageArray[x]))
								.getKeyCode());

					} catch (Exception e) {
						code = KeyStroke.getKeyStroke(messageArray[x], 0)
								.getKeyCode();
					}
					robot.keyPress(code);
					robot.setAutoDelay(0);
					System.out.println(robot.getAutoDelay());
					System.out.println("RELEASED KEY " + code);
					if (shift) {
						robot.keyRelease(KeyEvent.VK_SHIFT);
						shift = false;
					}

					//
				}
				if (dosend) {
					robot.keyPress(KeyEvent.VK_ENTER);
					robot.keyRelease(KeyEvent.VK_ENTER);

				}

			}
		} catch (Exception e) {

		}
	}

	public void keyPressed(KeyEvent arg0) {
		int keyCode = arg0.getKeyCode();
		if (keyCode == KeyEvent.VK_F12) {
			busy = false;
		}

	}

	// Unused...
	public void keyReleased(KeyEvent arg0) {
	}

	// Unused...
	public void keyTyped(KeyEvent arg0) {
	}
}
